﻿using System;
using System.IO;
using System.Text;

namespace SmartSiteManagementSystem.Appweb.Common
{
    using System.Collections;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public static class JsonExtensionMethods
    {
        /// <summary>
        /// 将对象转化为json，使用JsonConvert.SerializeObject
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static String ToJson(this object item)
        {
            return ToJson(item, null);

        }
        public static String ToJson(this object item, JsonConverter customConvert)
        {

            IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
            //这里使用自定义日期格式，如果不使用的话，默认是ISO8601格式           
            timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";

            StringBuilder sbJSON;
            string rawJSON;
            if (customConvert == null)
            {
                rawJSON = JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented, timeConverter);
            }
            else
            {
                rawJSON = JsonConvert.SerializeObject(item, Newtonsoft.Json.Formatting.Indented, timeConverter, customConvert);
            }

            StringWriter sw = new StringWriter();
            JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            writer.WriteRaw(rawJSON);
            writer.Flush();

            sbJSON = sw.GetStringBuilder();

            return sbJSON.ToString();
        }
        /// <summary>
        /// 将json字符串转化成指定的对象
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static T JsonToObject<T>(this string item)
        {
            return JsonConvert.DeserializeObject<T>(item);
        }

    
    }
}
